<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
  <head>
    <title>phastregex.  Regular expression genome search with phastcon conservation scores.</title>
    <meta http-equiv="Content-Type" content ="text/html; charset=utf-8">
    <link rel="stylesheet" href="phastregexjw.css" type="text/css">
    <?php include('jasonweirather.php'); ?>
  </head>
  <body>
    <?php
      $rname = rand();
      $tname = date('Y-m-d');
      $basename="phastregexOut_" . "$rname" . "_" . "$tname";
      $outputtable = $basename . ".table.php"; # we will rack up the awesome table to display here.
      $fasta = $_POST["fasta"];  
      $chrloc = $_POST["chrloc"];
      $chrloc = checklocation($chrloc);
      $regex1 = $_POST["regex1"];
      $regex1 = checkregex($regex1);
      $doevalue = 0;
      if($_POST["evalue"] == "YES") { $doevalue = 1; }
      $dowholegenome = $_POST["wholegenome"];
      $inputspecies=$_POST["speciesdropdown"];
      $inputspecies = checkinputspecies($inputspecies);
      if($inputspecies == NULL) { $species  = "danrer4"; }
      else {
        if(preg_match('/^(\w+)\s+/',$inputspecies,$matches) > 0) {
          $species = strtolower($matches[1]);
        } else { $species = "danrer4"; }
      }
        
      $matches1 = NULL;
      $matches2 = NULL;

      # go after conservation information now
      $fasta = preg_replace('/\r/',"",$fasta);
      $fastaCheck = NULL;
      $no_error = 0;
      if($fasta == NULL) { $no_error = 1; } # first time dont show an error
      if($fasta != NULL) { $fastaCheck = checkFasta($fasta); }
      if($fastaCheck != 'good'  && $fasta != NULL) { $fasta = NULL; }
      $ref_string='Jason Weirather 2010.
      <div id="ref_title">References:</div>
      <div class="ref_description">The UCSC genome browser linked by the results.</div>
      <div class="reference">Kent WJ, Sugnet CW, Furey TS, Roskin KM, Pringle TH, Zahler AM, Haussler D. <a href="http://www.genome.org/cgi/content/abstract/12/6/996">The human genome browser at UCSC.</a> Genome Res. 2002 Jun;12(6):996-1006.</div>
      <div class="ref_description">PhastCon conservation scores are the basis for the conservation estimate.</div>
      <div class="reference">Felsenstein J, Churchill GA. <a href="http://mbe.oxfordjournals.org/cgi/content/abstract/13/1/93">A Hidden Markov Model approach to variation among sites in rate of evolution.</a> Mol Biol Evol. 1996 Jan;13(1):93-104. </div>
      <div class="ref_description">The UCSC database contained all annotation information I used.</div>
      <div class="reference">Rhead B, Karolchik D, Kuhn RM, Hinrichs AS, Zweig AS, Fujita P, Diekhans M, Smith KE, Rosenbloom KR, Raney BJ, Pohl A, Pheasant M, Meyer L, Hsu F, Hillman-Jackson J, Harte RA, Giardine B, Dreszer T, Clawson H, Barber GP, Haussler D, Kent WJ. <a href="http://nar.oxfordjournals.org/cgi/content/full/38/suppl_1/D613">The UCSC Genome Browser database: update 2010.</a> Nucleic Acids Res. 2010 Jan;38(Database issue):D613-9. Epub 2009 Nov 11.</div>
      <div class="ref_description">The Human Genome Consorium for the human genome.</div>
      <div class="reference">The Genome Sequencing Consortium. <a href="http://www.nature.com/nature/journal/v409/n6822/abs/409860a0.html">Initial sequencing and analysis of the human genome.</a> Nature. 2001 Feb 15;409(6822):860-921. </div>
      <div class="ref_description">The Mouse Genome Cosortium for the mouse genome.</div>
      <div class="reference">Mouse Genome Sequencing Consortium. <a href="http://www.nature.com/nature/mousegenome/">Initial sequencing and comparative analysis of the mouse genome.</a> Nature, 420, 520-562 (2002).</div>
      <div class="ref_description">The International Fugu Genome Cosortium for the fugu genome.</div>
      <div class="reference">Aparicio S, et al. <a href="http://www.sciencemag.org/content/297/5585/1301.long">Whole-Genome Shotgun Assembly and Analysis of the Genome of <i>Fugu rubripes</i>.</a> Science, V. 297 no. 5585, 1301-1310 (2002).</div>
      <div class="ref_description">The Wellcome Trust Sanger Institute for the zebrafish genome.</div>
      <div class="reference">Wellcome Trust Sanger Institute. Jekosch K. The zebrafish genome project: sequence analysis and annotation. Methods Cell Biol. 2004;77:225-39.</div>';
      $title=htmlentities($_POST["title"]);
      $haveinputs = 0;
      if($title != NULL && $regex1 != NULL && $species != NULL && ($dowholegenome != NULL || $fasta != NULL || $chrloc != NULL)) {
        $haveinputs = 1;
      }
      if($haveinputs == 0) {
        echo "<div id=\"main_page_one\">\n";
        
      }
      if($haveinputs == 1) {
        echo "<div id=\"main_page_two\">\n";
      }
      echo "      <div id=\"top_title\">Find a perl format regular expression in a genomic sequence and look for conservation.  Determine how often you expect to observe that regular expression in a random sequence of the same length and GC content.</div>\n";
      if($haveinputs == 1) {
        $visBlast2path = "/home/x/Code/VISBLASTWEB";
        $workingdirectory = "/home/x/Public/phastregex/work";
        $working_address = "http://localhost/phastregex/work";
        #make the fasta based off the base name
        $fastafilename = "$workingdirectory/$basename.fasta";
        ##$fh = fopen($fastafilename,'w') or die ("can't open file");
        ##fwrite($fh,$fasta);
        ##fclose($fh);
        $fh = fopen("$workingdirectory/$outputtable",'w') or die ("can't open file");
        $title_line = "<div id=\"run_title\">$title</div>\n";
        fwrite($fh,$title_line);
        $date_line = "<div id=\"run_date\">$tname</div>\n";
        fwrite($fh,$date_line);
        $species_line = "<div id=\"run_species\">$inputspecies</div>\n";
        fwrite($fh,$species_line);
        ##$command = "$visBlast2path" . "/visBlast2.pl -i $workingdirectory/$basename.fasta -e $evalue --svg $workingdirectory/$basename.svg --png $workingdirectory/$basename.png --dot $workingdirectory/$basename.dot -o $workingdirectory/$basename.result --ivalue $ivalue $autocolor";
        ##$future_html_command = "$visBlast2path" . "/makehtml.pl $basename $evalue_string $ivalue_string > work/$basename.html";
        flush();
        sleep(1);
        echo "      <div id=\"failsafe_announce\">Be patient with large requests.  After completion, results are displayed below.  They will be availible after completion at the following address even if your connection is lost.<br><span class=\"no_click_url\">$working_address" . "/$basename.php</span></div>\n";
        flush(); #display so far
        sleep(2);
        if($chrloc != NULL) {
          $ucscdatabase = "danRer4";
          if($species == "danrer4") { $ucscdatabase = "danRer4"; }
          if($species == "hg18") { $ucscdatabase = "hg18"; }
          if($species == "mm9") { $ucscdatabase = "mm9"; }
          if($species == "fr2") { $ucscdatabase = "fr2"; }
          $ucsclink = "http://genome.ucsc.edu/cgi-bin/hgTracks?db=$ucscdatabase&position=$chrloc";
          $location_line = "<div id=\"search_location\"><a href=\"$ucsclink\">$chrloc</a></div>";
          fwrite($fh,$location_line);
          find_location($chrloc,$species,$regex1,$fh,$doevalue);
        }
        $last_line = "\n";
        fwrite($fh,$last_line);
        fclose($fh);
        $fphp = fopen("$workingdirectory/$basename.php",'w') or die ("can't open file");
        $archive_line = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
  <head>
    <title>phastregex.  Regular expression genome search with phastcon conservation scores.</title>
    <meta http-equiv="Content-Type" content ="text/html; charset=utf-8">
    <link rel="stylesheet" href="../phastregexjw.css" type="text/css">
    <?php include("../jasonweirather.php"); ?>
  </head>
  <body>
    <div id="archive_output">
      <?php include("' . $outputtable . '"); ?>
      <div id="reference_block">' . $ref_string . '</div>
    </div>
  </body>
</html>
';
        fwrite($fphp,$archive_line);
        fclose($fphp);
        echo "      <div id=\"output_title\">OUTPUT</div>\n";
        include("$workingdirectory/$outputtable");
        echo "      <div id=\"reference_block\">$ref_string</div>\n";
      } else {
        if($haveinputs == 0 && $no_error == 0) {
          echo "<div id=\"problem\">Error, Fix your inputs please. ";
          if($fastaCheck != NULL && $fastaCheck != 'good') { echo "<br>Specifically, " . $fastaCheck; }
          echo "</div>";
        }
      } 
      if($_POST['title']==NULL) { $titledisplay = "irf6 plus 100kb"; }
      else { $titledisplay = $_POST['title']; }
      if($_POST['regex1']==NULL) { $regex1display = "/[ACGT][CAT][AGT]A[CT]CGA[AT]AC[CT][ACTG]|[ACGT][AG]GT[AT]TCG[AG]T[ACT][ATG][ACGT]/"; }
      else { $regex1display = $_POST['regex1']; }
      if($_POST['chrloc']==NULL) { $locationdisplay = "chr22:1,268,701-1,499,464"; }
      else { $locationdisplay = $_POST['chrloc']; }
      echo ('
      <div id="main_logo_block"></div>
      <div id="input_title">INPUT</div>
      <div id="input_form">
        <form action="'.$self.'" method="post">
          <span class="form_label">Title: </span><input type="text" name="title" value="' . $titledisplay . '" id="title_text_box"><br>
          <div id="paramater_row">
            <div class="text_input"><span class="form_label">Regular expression:<br></span><input type="text" name="regex1" value="'. $regex1display . '" id="regex1_box"><br><span class="side_note">Remeber to include your reverse complement regular expression when applicable.</span></div>
       ');
        #    <div class = "form_label"><br>Enter either location (with species), whole genome (with species), or your own fasta file...</div>
        echo ('<div class="text_input"><span class="form_label">Select Species:<br></span><select id="species_menu" name="speciesdropdown">');
                 if($inputspecies != NULL) { echo('<option value="' . $inputspecies . '">'.$inputspecies.'</option>'); }
        echo('         <option value="danRer4 Zebrafish">danRer4 Zebrafish</option>
                 <option value="hg18 Human">hg18 Human</option>
                 <option value="mm9 Mouse">mm9 Mouse</option>
                 <option value="fr2 Fugu">fr2 Fugu</option>
               </select></div>
            <div class="text_input"><span class="form_label">Location:</span><br><input type="text" name="chrloc" value="' . $locationdisplay . '" id="chrloc_box"></div>
            <div class="text_input"><span class="form_label"><input id="evalue_box" type="checkbox" name="evalue" value="YES">Higher resolution E values</span> <span class="side_note">(increases computational time)</span></div>
        ');
        #    <div id="wholegenome_checkbox"><span class="form_label">or whole genome </span><input type="checkbox" id="ibox" name="wholegenome" value="dogenome"></div>
        echo ('
          </div>
        ');
         # <div id="fasta_input">
         #   <span class="form_label">or Fasta</span> (no conservation data if you use a Fasta instead of a location)<br>
         #   <textarea name="fasta" id="fasin" value="5"></textarea><br><br>
         echo('
            <div id="submit_input"><input id="submit_button" type="submit" value="Submit">&nbsp&nbsp<a href="phastregexhelp.html" id="help">?</a></div>
         ');
         # </div>
        echo ('
        </form>
      </div>
    ');
      if($fasta == NULL || $title == NULL || $evalue == NULL) {
        echo "<div id=\"reference_block\">$ref_string</div>\n";
      }
      echo "</div>\n";
      function find_conservation($location) {
        $location_array = parse_location_string($location);
        $chromosome = $location_array[1];
        $start = $location_array[2];
        $finish = $location_array[3];
        $database = "conservation";
        include("dbconnect.php");
        ### put in control structure here to look for each start and stop
        $low_table = "danrer4_vertebrate_05_1";
        $mid_table = "danrer4_vertebrate_4_5";
        $high_table = "danrer4_vertebrate_8_9";
        $match_start = $matches1[0][0][1];
        $match_finish = $matches1[0][0][2]-1;
        #echo "matches: <br>\n";
        #print_r($matches1);
        #echo "<br>";
        $query = "SELECT start,finish FROM $low_table WHERE chromosome=\"$chromosome\" AND (";
        $query .= "(start <= \"$match_finish\" AND start >= \"$match_start\") OR "; # look within
        $query .= "(finish >= \"$match_start\" AND finish <= \"$match_finish\")"; # look within
        $query .= " )LIMIT 1";
        #echo "$query<br>\n";
        $result = mysql_query($query);
        $row = mysql_fetch_object($result);
        if($row == NULL) {
          echo "empty query fetch and uncompress sequence. fail.<br>\n";
          die;
        }
        
        #results are for this specifc chromosome.
        
        
      }
      function parse_location_string($location) {
        $location = preg_replace('/,/','',$location);
        if(preg_match('/(chr\S+)\s*:\s*(\d+)\s*-\s*(\d+)/i',$location,$matches) > 0) {
          $chromosome = $matches[1];
          $start = $matches[2];
          $finish = $matches[3];
        } else { 
          echo "location malformed. fail.<br>\n";
          die; 
        }
        return $matches;
      }
      function find_location($location,$species,$regex1,$fh,$doevalue) {
        $database = "compressed_genomes";
        include("dbconnect.php");
        #get the location data out of the string.  get rid of commas first we won't use them
        $species = mysql_real_escape_string($species);
        #$chromosome = "chr20";
        #$start = 1;
        #$finish = 1;
        $location_array = parse_location_string($location);
        $chromosome = mysql_real_escape_string($location_array[1]);
        $start = mysql_real_escape_string($location_array[2]);
        $finish = mysql_real_escape_string($location_array[3]);
        #echo "chr $chromosome<br>\nst $start<br>\nfi $finish<br>\n";
        #swap start and finish if start is greater than finish
        if($start > $finish) {
          $temp = $finish;
          $finish = $start;
          $start = $temp;
        }
        #print_r($matches);  #debug
        #now we can get the sequence from the database for this location
        $query = "SELECT SUBSTRING(UNCOMPRESS(sequence),$start,$finish-$start+1) as outseq FROM $species WHERE chromosome=\"$chromosome\" LIMIT 1";
        $result = mysql_query($query);
        $row = mysql_fetch_object($result);
        if($row == NULL) {
          echo "empty query fetch and uncompress sequence. fail.<br>\n";
        }
        $sequence = $row->outseq;
        #lets calculate gc content
        $gccontent = get_gc_content($sequence);
        $evalue_multiplicity = 2;
        if($doevalue == 1) { $evalue_multiplicity = 100; }
        $random_length = strlen($sequence)*$evalue_multiplicity;
        $randseq= '';
        while(strlen($randseq) < $random_length) {
          $randseq .= random_dna_sequence($gccontent,10000); # random sequence with appropriate gc content
        }
        #echo "gc: $gccontent<br>\n";
        #echo "$sequence<br>\n";
        $randmatch1count = preg_match_all($regex1,$randseq,$randmatch);
        #now lets find all our matches and locations for each regular expression here.
        #now get the length of sequences in each category of conservation.
        $matches1 = matchreg($regex1,$sequence,$start,$finish);
        mysql_close();
        ###### now lets try to get some information on conservation from each of these things
        #query about conservation for each potential element.
        if($species == "danrer4") {
          $low_table = "danrer4_vertebrate_05_1";
          $mid_table = "danrer4_vertebrate_4_5";
          $high_table = "danrer4_vertebrate_8_9";
        }
        if($species == "hg18") {
          $low_table = "hg18_vertebrate_05_1";
          $mid_table = "hg18__vertebrate_4_5";
          $high_table = "hg18__vertebrate_8_9";
        }
        if($species == "mm9") {
          $low_table = "mm9_vertebrate_05_1";
          $mid_table = "mm9_vertebrate_4_5";
          $high_table = "mm9_vertebrate_8_9";
        }
        if($species == "fr2") {
          $low_table = "fr2_vertebrate_05_1";
          $mid_table = "fr2_vertebrate_4_5";
          $high_table = "fr2_vertebrate_8_9";
        }
        $low_conservation_length = find_conservation_length($location,$low_table);
        $mid_conservation_length = find_conservation_length($location,$mid_table);
        $high_conservation_length = find_conservation_length($location,$high_table);

        $random_frequency = $randmatch1count/strlen($randseq);
        #echo "out of a random sequence of length " . strlen($randseq) . "<br>\n";
        #echo "$randseq<br>\n";
        #echo "given gc fraction: $gccontent<br>\n";
        #echo "expected average occurance frequency:  $random_frequency<br>\n";
        $random_total = $random_frequency *strlen($sequence);
        $random_low = $random_frequency*$low_conservation_length;
        $random_mid = $random_frequency*$mid_conservation_length;
        $random_high = $random_frequency*$high_conservation_length;
        
        #echo "expected total occurances: $random_total<br>\n";
        #echo "expected low occurances: $random_low<br>\n";
        #echo "expected mid occurances: $random_mid<br>\n";
        #echo "expected high occurances: $random_high<br>\n";

        if(count($matches1[0]) > 0) { # we will print a table for the regular expression
          $regex_line = "<div class=\"regex_title\">$regex1</div>\n<table id=\"regex1_table\" class=\"regex_table\">\n";
          $regex_line .= "<tr class=\"head_row\"><td>location</td><td>match</td><td>cons</td><td>E value</td><td>upstream of</td><td>downstream of</td><td>inside</td></tr>\n";
          fwrite($fh,$regex_line);
        }
        for($i = 0; $i < count($matches1[0]); $i++) { #for each match.
          $database = "conservation";
          include("dbconnect.php");
          $match_start = $matches1[0][$i][1];
          $match_finish = $matches1[0][$i][2]-1;
          $query = form_conservation_query($low_table,$chromosome,$match_start,$match_finish);
          $result = mysql_query($query);
          if(mysql_num_rows($result) > 0) { $matches1[0][$i][3] = 1; } 
          else { $matches[0][$i][3] = 0; }
            # again, but this time with the mid table
          $query = form_conservation_query($mid_table,$chromosome,$match_start,$match_finish);
          $result = mysql_query($query);
          if(mysql_num_rows($result) > 0) { $matches1[0][$i][3] = 2; }
            # finally for high conservation
          $query = form_conservation_query($high_table,$chromosome,$match_start,$match_finish);
          $result = mysql_query($query);
          if(mysql_num_rows($result) > 0) { $matches1[0][$i][3] = 3; }
          #echo "$query<br>finds conservation: " . $matches1[0][$i][3] . "<br>\n";
          mysql_close();
          # lets start this table off
          $conservation = "";
          if($matches1[0][$i][3] == 1) { $conservation = "<span class=\"low_conservation\">0.1</span>"; }
          if($matches1[0][$i][3] == 2) { $conservation = "<span class=\"mid_conservation\">0.5</span>"; }
          if($matches1[0][$i][3] == 3) { $conservation = "<span class=\"high_conservation\">0.9</span>"; }
          $evalue = $random_total;
          if($matches1[0][$i][3] == 1) { $evalue = $random_low; }
          if($matches1[0][$i][3] == 2) { $evalue = $random_mid; }
          if($matches1[0][$i][3] == 3) { $evalue = $random_high; }
          if($evalue > 0.001) { $evalue = sprintf("%.2f",$evalue); }
          else { $evalue = sprintf("%.2e",$evalue); }
          if($evalue >= 1000) { $evalue = sprintf("%.2e",$evalue); }
          if($doevalue == 0 && $evalue < 1) { $evalue = "< 1"; }
          $ucscdatabase = "danRer4";
          if($species == "danrer4") { $ucscdatabase = "danRer4"; }
          if($species == "hg18") { $ucscdatabase = "hg18"; }
          if($species == "mm9") { $ucscdatabase = "mm9"; }
          if($species == "fr2") { $ucscdatabase = "fr2"; }
          $ucsclink = "http://genome.ucsc.edu/cgi-bin/hgTracks?db=$ucscdatabase&position=$chromosome:$match_start-$match_finish";
          $row_start = "<tr class=\"" . even_odd_row_class($i) . "\"><td><a href=\"$ucsclink\">$chromosome:$match_start-$match_finish</a></td><td>" . $matches1[0][$i][0] . "</td><td>$conservation</td><td>$evalue</td>";
          fwrite($fh,$row_start);
          $features = find_features($chromosome,$match_start,$match_finish,$fh,$species);
          #$row = mysql_fetch_object($result);
        }
        if(count($matches1[0]) > 0) { # we will print a table for the regular expression
          $tableend_line = "\n</table>\n";
          fwrite($fh,$tableend_line);
        }
        
      }
      function find_conservation_length($location,$tablename) {
        $database = "conservation";
        include("dbconnect.php");
        $location_array = parse_location_string($location);
        $chromosome = $location_array[1];
        $mystart = $location_array[2];
        $myfinish = $location_array[3];
        $query = "SELECT (finish-start) as con_size FROM $tablename WHERE chromosome = \"$chromosome\" AND start > $mystart AND finish < $myfinish"; # situation where a conservation track is contained in here
        $size = 0;
        $result = mysql_query($query);
        while($row = mysql_fetch_object($result)) {
          $size += $row->con_size;
        }
        #get the portion of the start
        $query = "SELECT finish FROM $tablename WHERE chromosome = \"$chromosome\" AND start < $mystart AND finish > $mystart LIMIT 1";
        $result = mysql_query($query);
        while($row = mysql_fetch_object($result)) {
          $size += $row->finish-$mystart;
        }
        #get the portion of the finish
        $query = "SELECT start FROM $tablename WHERE chromosome = \"$chromosome\" AND start < $myfinish AND finish > $myfinish LIMIT 1";
        $result = mysql_query($query);
        while($row = mysql_fetch_object($result)) {
          $size += $myfinish-$row->start;
        }
        mysql_close();
        #echo "size: $size<br>\n";
        return $size;
      }
      function random_dna_sequence($gccontent,$length) {
        $seq = '';
        $atcontent = 1-$gccontent;
        $gcutoff = $gccontent/2;
        $ccutoff = $gccontent;
        $acutoff = $gccontent+($atcontent/2);
        #echo"g $gcutoff c $ccutoff a $acutoff t 1<br>\n";
        for($i = 0; $i < $length; $i++) {
          $rand = random_float();
          if($rand >= 0 && $rand < $gcutoff) { $seq .= "G"; }
          if($rand >= $gcutoff && $rand < $ccutoff) { $seq .= "C"; }
          if($rand >= $ccutoff && $rand < $acutoff) { $seq .= "A"; }
          if($rand >= $acutoff && $rand <= 1) { $seq .= "T"; }
        }
        return $seq;
      }
      function random_float () {
        return (float)rand()/(float)getrandmax();
      }
      function get_gc_content ($sequence) {
        $purified_sequence = preg_replace('/[![ACTG]]/',"",$sequence);#remove anything other ACTG
        $fulllength = strlen($purified_sequence);
        $gclength = strlen(preg_replace('/[AT]/',"",$purified_sequence));
        return $gclength/$fulllength;
        #echo "$purified_sequence<br>\n";
      }
      function find_features($chromosome,$match_start,$match_finish,$fh,$species) {
        $upstream_distance = 100000;
        $downstream_distance = 100000;
        #this function will try and describe where it is.  We will use the 
        #mysql refGene.sql database from UCSC for this part.  need to add multi species support later 
        $database = "compressed_genomes";
        include("dbconnect.php");
          #is it upstream from a gene?
        $query = "SELECT strand, txStart, txEnd, name, name2, 'upstream' as relative_location FROM $species" . "_genes WHERE chrom = \"$chromosome\" AND (";
        $query .= "(strand = \"+\" AND $match_start < txStart AND $match_start > (txStart-$upstream_distance)) OR ";
        $query .= "(strand = \"-\" AND $match_finish > txEnd AND $match_finish < (txEnd+$upstream_distance))";
        $query .= ")";
        #echo "upstream query: $query<br>\n";
        $result = mysql_query($query);
        $upstream_line = "";
        while($row = mysql_fetch_object($result)) {
          #see all the genes it is upstream of.
          $distance = 0;
          if($row->strand == '+') { $distance = $row->txStart-$match_finish; }
          else { $distance = $match_start-$row->txEnd; }
          $name = $row->name;
          $name2 = $row->name2;
          #echo "falls $distance bp upstream of $name, $name2<br>\n";
          $upstream_line .= "$name2 ($name) / $distance bp<br>";
        }
        preg_match('/^(.*)<br>$/',$upstream_line,$upmatch);
        $upstream_line = "<td>" . $upmatch[1] . "</td>";
        fwrite($fh,$upstream_line);
          #is it downstream from a gene?
        $query = "SELECT strand, txStart, txEnd, name, name2, 'downstream' as relative_location FROM $species"."_genes WHERE chrom = \"$chromosome\" AND (";
        $query .= "(strand = \"-\" AND $match_start < txStart AND $match_start > (txStart-$upstream_distance)) OR ";
        $query .= "(strand = \"+\" AND $match_finish > txEnd AND $match_finish < (txEnd+$upstream_distance))";
        $query .= ")";
        #echo "downstream query: $query<br>\n";
        $result = mysql_query($query);
        $downstream_line = "";
        while($row = mysql_fetch_object($result)) {
          #see all the genes it is downstream of.
          $distance = 0;
          if($row->strand == '+') { $distance = $match_start-$row->txEnd; }
          else { $distance = $row->txStart-$match_finish; }
          $name = $row->name;
          $name2 = $row->name2;
          #echo "falls $distance bp downstream of $name, $name2<br>\n";
          $downstream_line .= "$name2 ($name) / $distance bp<br>";
        } 
        preg_match('/^(.*)<br>$/',$downstream_line,$downmatch);
        $downstream_line = "<td>" . $downmatch[1] . "</td>";
        fwrite($fh,$downstream_line);
          #is it in a gene?
        $query = "SELECT strand, name, name2, 'inside' as relative_location, exonCount, exonStarts, exonEnds FROM $species"."_genes WHERE chrom = \"$chromosome\" AND (";
        $query .= "($match_finish > txStart AND $match_start < txEnd)";
        $query .= ")";
        #echo "inside query: $query<br>\n";
        $result = mysql_query($query);
        $inside_line = "";
        #while($row = mysql_fetch_object($result)) {
        #  $name = $row->name;
        #  $name2 = $row->name2;
        #  echo "falls inside $name, $name2<br>\n";
        #}
        #if it is in a gene, we need to figure out whether or not its in an exon for each gene that its in.
        while ($row = mysql_fetch_object($result)) { #for each of the genes
          $name = $row->name;
          $name2 = $row->name2;
          $exonCount = $row->exonCount;
          $exonStarts = preg_split('/,/',$row->exonStarts);
          $exonEnds = preg_split('/,/',$row->exonEnds);
          $inside_line .= "$name2 ($name)";
          for($i = 0; $i < $exonCount; $i++) {
            #now see if it dips into any exons.
            #echo "check exons<br>\n";
            if(($match_start < $exonStarts[$i] && $match_finish > $exonStarts[$i]) || ($match_finish > $exonEnds[$i] && $match_start < $exonEnds[$i]) || ($match_start > $exonStarts[$i] && $match_finish < $exonEnds[$i]) || ($match_start < $exonStarts[$i] && $match_finish > $exonEnds[$i])) {
               #it dips into an exon
               #echo "in exon " . ($i+1) . "<br>\n";
               $inside_line .= " / exon " . ($i+1);
            }
            #if there is a next exon, check the intron
            if($i < $exonCount-1) {
              #see if it dips into any introns
              if(($match_start < $exonEnds[$i] && $match_finish > $exonEnds[$i]) || ($match_start < $exonStarts[$i+1] && $match_finish > $exonStarts[$i+1]) || ($match_start > $exonEnds[$i] && $match_finish < $exonStarts[$i+1]) || ($match_start < $exonEnds[$i] && $match_finish > $exonStarts[$i+1])) {
                #it dips into an intron
                #echo "in intron " . ($i+1) . "<br>\n";
                $inside_line .= " / intron " . ($i+1);
              }
            }
          }
          $inside_line .= "<br>";
        }
        preg_match('/^(.*)<br>$/',$inside_line,$inmatch);
        $inside_line = "<td>" . $inmatch[1] . "</td></tr>";
        #echo "inside: $inside_line<br>\n";
        fwrite($fh,$inside_line);
        return;
      }
      function even_odd_row_class($i) {
        if(($i%2)==0) { return "even_row"; }
        else { return "odd_row"; } 
      }
      function form_conservation_query($table,$chromosome,$match_start,$match_finish) {
        $query = "SELECT start, finish FROM $table WHERE chromosome =\"$chromosome\" AND (";
        $query .= "($match_start >= start AND $match_start <= finish) OR "; # look allow overlap start
        $query .= "($match_finish >= start AND $match_finish <= finish) OR "; # look allow overlap finish
        $query .= "($match_start >= start AND $match_finish <= finish) OR "; # look allow overlab both
        $query .= "($match_start <= start AND $match_finish >= finish)"; # look allow overlab other way
        $query .= ") LIMIT 1";
        return $query;
      }
      function matchreg($regex,$sequence,$start,$finish) {
        $match_count = preg_match_all($regex,$sequence,$matches,PREG_OFFSET_CAPTURE);
        #print_r($matches);
        #echo "$sequence<br>\n";
        for($i = 0; $i < $match_count; $i++) {
          $matches[0][$i][1] += $start;
          $matches[0][$i][2] = $matches[0][$i][1]+strlen($matches[0][$i][0]);
          #echo "match " . $matches[0][$i][1] . " " . $matches[0][$i][2] . "<br>\n";
        }
        #print_r($matches);
        #echo "<br>\n";
        return $matches;
      }
      function checkinputspecies($species) {
        if($species==NULL) { return $species; }
        if(preg_match('/^\w{1,50}\s+\w{1,50}$/',$species) > 0) { return $species; }
        else { return NULL; }
      }
      function checkregex($regex) {
        #no cleaning up done here yet.
        return $regex;
      }
      function checklocation($location) {
        if($location == NULL) { return $location; }
        #something is in the location
        $location = preg_replace('/,/','',$location);
        if(preg_match('/^\s*chr\w+\s*:\s*\d+\s*-\s*\d+\s*$/i',$location) > 0) { return $location; }
        else { return NULL; }
      }
      function checkEvalue($ineval) {
        if(is_numeric($ineval)) { $outeval =(float)$ineval; }
        else { $outeval = NULL; }
        return $outeval;
      }
      function checkFasta($fasta) {
      $max_sequence_length = 10000;
      $mix_sequence_length = 10;
      $max_number_of_sequences = 50000;
      $min_number_of_sequences = 2;
        $check = 'good';
        $lines = explode("\n",$fasta);
        foreach($lines as &$line) {
           $line = trim($line);
           if(preg_match('/^>\S+/',$line)) { } #proper title
           else { 
             if(!preg_match('/\S/',$line)) {  }#ok if its empty
             else {
               if(preg_match('/^[GAVLIMFWPSTCYNQDEKRHUX\*gavlimfwpstcynqdekrhux\s]+$/',$line)) {  #ok if its a gene or a nucleotide with whitespace on the ends
               } else { 
                 $check = "Error - Illegal Character: <br>" . wordwrap(htmlentities($line),50,"<br>",1);
               }
             }
           }
        }
        unset($line);
        $lines = preg_split('/>.*\n/',$fasta);
        if(sizeof($lines) > $max_number_of_sequences) { $check = "Error - Too many sequences.  " . sizeof($lines) . " exceeds $max_number_of_sequences maximum number of sequences."; }
        if(sizeof($lines) < $min_number_of_sequences) { $check = "Error - Too few sequences.  " . sizeof($lines) . " is less than $min_number_of_sequences minimum number of sequences."; }
        foreach($lines as &$line) {
          $one_seq = preg_replace('/\n|\s/',"",$line);
          if(strlen($one_seq) > $max_sequence_length) { $check = "Error - Sequence needs to be shorter than $max_sequence_length characters: <br>" . wordwrap(htmlentities($one_seq),50,"<br>",1); }
          if(strlen($one_seq) < $min_sequence_length) { $check = "Error - Sequence needs to be longer than $min_sequence_length characters: <br>" . wordwrap(htmlentities($one_seq),50,"<br>",1); }
        }
        unset($line);
        return $check;
      }
    ?>
  </body>
</html> 
